package com.cn.yds.bdy.controller.exception;

import com.cn.yds.bdy.vo.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

@RestControllerAdvice
public class BindExceptionHanlder {

    private static final Logger logger = LoggerFactory.getLogger(BindExceptionHanlder.class);

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseResult handleBindException(MethodArgumentNotValidException ex) {

        FieldError fieldError = ex.getBindingResult().getFieldError();
        StringBuilder sb = new StringBuilder();
        Object value = fieldError.getRejectedValue();
        if (Objects.isNull(value) || StringUtils.isEmpty(value)) {
            value = "' '";
        }
        sb.append(fieldError.getField()).append("=[").append(value).append("], ")
                .append(fieldError.getDefaultMessage());

        String bindFailMessage = sb.toString();
        logger.info("Controller bind data exception : {} ", bindFailMessage);

        return ResponseResult.fail(bindFailMessage);

    }


    @ExceptionHandler(value = Exception.class)
    public ResponseResult handleBindException(Exception ex) {

        logger.info("Controller exception : ==> ", ex);
        return ResponseResult.fail(ex.toString());

    }
}
